//
//  LLLabelAddVM.m
//  LLLabel
//
//  Created by LQ on 2020/12/9.
//

#import "WKLabelAddVM.h"
#import "WKLabelCell.h"
#import "WKLabelNameSettingCell.h"
#import "WKLabelAddCell.h"
#import "WKLabelMemberCell.h"
#import "WKLabelNameSettingInputCell.h"
@interface WKLabelAddVM ()

@property(nonatomic,strong) NSMutableArray *headerItems;


@end

@implementation WKLabelAddVM

- (NSArray<NSDictionary *> *)tableSectionMaps {
    [self.headerItems removeAllObjects];
    
    NSMutableArray *items = [NSMutableArray array];
    __weak typeof(self) weakSelf = self;
    [self.headerItems addObject: @{
        @"height":@(0.1f),
        @"title": LLang(@"标签名字"),
        @"items": @[
                @{
                    @"class":WKLabelNameSettingInputModel.class,
                    @"value": self.labelName?:@"",
                    @"placeholder":LLang(@"未设置标签名字"),
                    @"showArrow":@(false),
                    @"onChange":^(NSString *value){
                        weakSelf.labelName = value;
                        if(weakSelf.onUpdateFinishBtn) {
                            weakSelf.onUpdateFinishBtn();
                        }
                    },
                    @"onClick":^{
                        WKInputVC *vc = [WKInputVC new];
                        vc.maxLength = 10;
                        vc.placeholder = LLang(@"例如家人、朋友");
                        vc.defaultValue = weakSelf.labelName;
                        [vc setOnFinish:^(NSString * _Nonnull value) {
                            [[WKNavigationManager shared] popViewControllerAnimated:YES];
                            weakSelf.labelName = value;
                            [weakSelf reloadData];
                        }];
                        [[WKNavigationManager shared] pushViewController:vc animated:YES];
                    }
                }
        ],
    }];
    
    [self.headerItems addObject:  @{
        @"height":@(0.1f),
        @"title": [NSString stringWithFormat:LLang(@"标签成员（%lu）"),(unsigned long)self.memberItems.count],
        @"items": @[
                @{
                    @"class": WKLabelAddModel.class,
                    @"title": LLang(@"添加成员"),
                    @"onClick":^{
                        NSMutableArray<NSString*> *selecteds = [NSMutableArray array];
                        if(weakSelf.memberItems) {
                            for (WKChannelInfo *channelInfo in weakSelf.memberItems) {
                                [selecteds addObject:channelInfo.channel.channelId];
                            }
                        }
                        [[WKApp shared] invoke:WKPOINT_CONTACTS_SELECT param:@{
                            @"selecteds":selecteds,
                            @"on_finished":^(NSArray<NSString*> *uids){
                                [[WKNavigationManager shared] popViewControllerAnimated:YES];
                                if(uids && uids.count>0) {
                                    NSMutableArray *items = [NSMutableArray array];
                                    for (NSString *uid in uids) {
                                       WKChannelInfo *channelInfo = [[WKSDK shared].channelManager getChannelInfo:[WKChannel personWithChannelID:uid]];
                                        if(channelInfo) {
                                            [items addObject:channelInfo];
                                        }
                                    }
                                    self.memberItems = items;
                                    [weakSelf refreshPinYin];
                                }
                            }
                        }];
                    },
                },
        ],
    }];
    
    [items addObjectsFromArray:self.headerItems];
    
    NSMutableArray *members = [NSMutableArray array];
    if(self.members && self.members.count>0) {
        for (NSInteger i=0; i<self.members.count; i++) {
            NSArray *items = self.members[i];
            NSMutableArray *dataArray = [NSMutableArray array];
            NSString *pinYin = self.sectionTitleArr[i];
            if(items && items.count>0) {
                for (NSInteger j=0; j<items.count; j++) {
                    WKChannelInfo *item = items[j];
                    [dataArray addObject:@{
                        @"class": WKLabelMemberModel.class,
                        @"firstPinYIn": j==0?pinYin:@" ",
                        @"name": item.displayName?:@"",
                        @"avatarURL":[WKAvatarUtil getAvatar:item.channel.channelId],
                        @"onClick":^{
                        [[WKApp shared] invoke:WKPOINT_USER_INFO param:@{
                            @"uid": item.channel.channelId?:@"",
                        }];
                        }
                    }];
                }
            }
            [members addObject:@{
                @"height":@(0.01f),
                @"items": dataArray,
            }];
        }
    }
    
    [items addObjectsFromArray:members];
    
    return items;
}

- (void)setLabel:(WKLabelResp *)label {
    _label = label;
    if(label) {
        self.labelName = label.name;
        NSMutableArray<WKChannelInfo*> *members = [NSMutableArray array];
        if(label.members) {
            for (NSString *uid in label.members) {
                WKChannelInfo *channelInfo =  [[WKSDK shared].channelManager getChannelInfo:[WKChannel personWithChannelID:uid]];
                if(channelInfo) {
                    [members addObject:channelInfo];
                }
            }
            self.memberItems = members;
            [self refreshPinYin];
        }
    }
}

-(void) refreshPinYin {
    __weak typeof(self) weakSelf = self;
    [WKChineseSort sortAndGroup:self.memberItems key:@"displayName" finish:^(bool isSuccess, NSMutableArray *unGroupArr, NSMutableArray *sectionTitleArr, NSMutableArray<NSMutableArray *> *sortedObjArr) {
        if(isSuccess) {
            weakSelf.sectionTitleArr = sectionTitleArr;
            weakSelf.members = [NSMutableArray arrayWithArray:sortedObjArr];
            [weakSelf reloadData];
        }
    }];
}

-(AnyPromise*) finishLabel {
    NSMutableArray *uids = [NSMutableArray array];
    if(self.memberItems) {
        for (WKChannelInfo *channelInfo in self.memberItems) {
            [uids addObject:channelInfo.channel.channelId];
        }
    }
    if(self.label) { // 更新
        return  [[WKAPIClient sharedClient] PUT:[NSString stringWithFormat:@"label/%@",self.label._id] parameters:@{
            @"name":self.labelName?:@"",
            @"member_uids": uids,
        }];
    }else{ // 添加
        return  [[WKAPIClient sharedClient] POST:@"label" parameters:@{
            @"name":self.labelName?:@"",
            @"member_uids": uids,
        }];
    }
   
}

-(void) removeMemberWithUID:(NSString *)uid {
    if(self.memberItems && self.memberItems.count>0) {
        NSInteger i= 0;
        for (WKChannelInfo *member in self.memberItems) {
            if([member.channel.channelId isEqualToString:uid]) {
                [self removeMember:i];
                return;
            }
            i++;
        }
    }
}

-(void) removeMember:(NSInteger)index {
    [self.memberItems removeObjectAtIndex:index];
    [self refreshPinYin];
}

- (NSMutableArray *)headerItems {
    if(!_headerItems) {
        _headerItems = [NSMutableArray array];
    }
    return _headerItems;
}

- (NSMutableArray*)members {
    if(!_members) {
        _members = [NSMutableArray array];
    }
    return _members;
}

- (NSMutableArray<WKChannelInfo *> *)memberItems {
    if(!_memberItems) {
        _memberItems = [NSMutableArray array];
    }
    return _memberItems;
}

- (NSInteger)headerCount {
    return self.headerItems.count;
}

@end
